package com.puff.web.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.puff.core.Puff;
import com.puff.framework.container.ExecutorContainer;

public class PuffDynamicExecutorProvider extends PuffExecutorProvider {

	@Override
	public Executor getExecutor(HttpServletRequest request, String requestURI) {
		Executor executor = super.getExecutor(request, requestURI);
		if (executor == null) {
			String[] arr = requestURI.split("/");
			List<Executor> dynamics = ExecutorContainer.getDynamic(arr.length - 1);
			if (dynamics != null) {
				String requestMethod = request.getMethod();
				each: for (Executor ec : dynamics) {
					if (!canInvoke(ec.requestMethod, requestMethod)) {
						continue;
					}
					String[] compare = ec.getCompare();
					int[] compareIdx = ec.getCompareIdx();
					for (int i = 0; i < compare.length;) {
						String m = compare[i];
						if (!m.equals(arr[compareIdx[i]])) {
							continue each;
						}
						if (++i == compare.length) {
							// 判断成功 提取参数
							StringBuilder param = new StringBuilder(64);
							int[] paramIdx = ec.getParamIdx();
							for (int j = 0; j < paramIdx.length;) {
								param.append(arr[paramIdx[j++]]);
								if (j < paramIdx.length) {
									param.append(Puff.getUrlParamSeparator());
								}
							}
							PuffContext.setUrlParam(param.toString());
							executor = ec;
							break each;
						}
					}
				}
			}
		}
		return executor;
	}

}
